package net.color4me.app.farmere.server;

import java.util.Date;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.color4me.app.farmere.Constant;
import net.color4me.app.farmere.entity.FarmUser;

import org.htmlparser.Parser;
import org.htmlparser.filters.CssSelectorNodeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.FormTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;

public class FarmerClient {
	private static final Logger log = Logger.getLogger(FarmerClient.class.getName());

	public FarmUser login(String user, String passwd) {
		SimpleHttpClient httpclient = new SimpleHttpClient("");

		FarmUser farmuser = new FarmUser();
		farmuser.setUser(user);
		//
		farmuser.setPassword(passwd);
		//
		farmuser.setLink("");
		farmuser.setCookieStr("");
		try {
			httpclient.fetch("http://m.xiaonei.com/wlogout.do");
			String loginPageString = httpclient.fetch(Constant.XIAONEI_URL);

			Parser parser = Parser.createParser(loginPageString, "UTF-8");
			String formActionString = "";

			NodeList nodeList = parser.parse(new TagNameFilter("form"));
			FormTag formTag = (FormTag) nodeList.elementAt(0);
			formActionString = formTag.getAttribute("action");

			if (formActionString.contains("whome.do")) {
				String poststr = formActionString + "&email=" + user + "&password=" + passwd;

				String indexPageString = httpclient.post(poststr);
				// farmuser.setCookieStr(httpclient.getCookiestr());
				parser = Parser.createParser(indexPageString, "UTF-8");

				NodeList happnodes = parser.parse(new CssSelectorNodeFilter("div.sec a"));
				SimpleNodeIterator happylinks = happnodes.elements();
				while (happylinks.hasMoreNodes()) {
					LinkTag hlink = (LinkTag) happylinks.nextNode();
					System.out.println(hlink.getLinkText() + hlink.getLink());
					if (hlink.getLinkText().equals("开心农场")) {
						String happylink = hlink.getLink();
						farmuser.setLink(happylink);
						httpclient.fetch(happylink);
						farmuser.setCookieStr(httpclient.getCookiestr());
						break;
					}
				}

			} else {
				logout(loginPageString);
			}
		} catch (Exception e) {
			log.warning("Parser Error");

		}

		return farmuser;

	}

	public String farmWork(FarmUser user) {
		String happyLink = user.getLink();
		String cookiestr = user.getCookieStr();
		StringBuffer sb = new StringBuffer();
		SimpleHttpClient httpClient = new SimpleHttpClient(cookiestr);
		try {

			sb.append("result:" + user.getUser() + "<br>" + happyLink);

			String responseHTML = httpClient.fetch(happyLink);
			// sb.append(responseHTML);
			// Get Field Status
			Parser parser = Parser.createParser(responseHTML, "UTF-8");

			NodeList nodeList = parser.parse(new CssSelectorNodeFilter("div.pager a"));

			SimpleNodeIterator filedList = nodeList.elements();

			Date nowDate = new Date();
			boolean needHarvest = false;
			// Robot works
			while (filedList.hasMoreNodes()) {
				LinkTag div = (LinkTag) filedList.nextNode();
				sb.append(div.getLink() + "<br>");
				Pattern pattern = Pattern.compile("act=([a-z]+)");
				Matcher matcher = pattern.matcher(div.getLink());
				if (matcher.find()) {
					String Op = matcher.group(1);
					System.out.print(Op);
					if (!Op.equalsIgnoreCase(Constant.OP_FERTILIZE)) {
						if (!Op.equalsIgnoreCase(Constant.OP_PLANTING)) {
							httpClient.fetch(Constant.APP_URL + div.getLink());
							log.info(nowDate.getTime() + ": " + Constant.OP_LIST.get(Op) + Op + "成功！");
							sb.append(nowDate.getTime() + ": " + Constant.OP_LIST.get(Op) + Op + "成功！" + "<br>");
						} else {
							doHarvest(div.getLink(), httpClient);
							needHarvest = true;
						}

					}
				}

			}

			// Logout

		} catch (ParserException e) {
			log.severe("Paser Error");
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();

	}
	// 临时改一下.一次只种植一个
	// 种植太多.服务器响应超时..就会失败
	public String doHarvest(String plantlink, SimpleHttpClient httpClient) {

		try {
			String plantingPageString = httpClient.fetch(Constant.APP_URL + plantlink);
			Parser parser = Parser.createParser(plantingPageString, "UTF-8");
			NodeList nodeList = parser.parse(new CssSelectorNodeFilter("div.nopad a"));
			SimpleNodeIterator plantingIterator = nodeList.elements();
			while (plantingIterator.hasMoreNodes()) {
				LinkTag oneTag = (LinkTag) plantingIterator.nextNode();
				if (oneTag.getLinkText().equals("种植")) {
					httpClient.fetch(Constant.APP_URL + oneTag.getLink());
					log.info("收获成功！");
					break;
				}
			}

		} catch (ParserException e) {
			log.severe("Paser Error");
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	public String logout(String htmlstr) {
		// Logout
		SimpleHttpClient httpClient = new SimpleHttpClient("");
		Parser parser3 = Parser.createParser(htmlstr, "UTF-8");
		try {
			NodeList quitList = parser3.parse(new CssSelectorNodeFilter("div#footer a"));

			SimpleNodeIterator utilList = quitList.elements();
			while (utilList.hasMoreNodes()) {
				LinkTag hlink = (LinkTag) utilList.nextNode();
				System.out.println(hlink.getLinkText() + hlink.getLink());
				if (hlink.getLinkText().equals("退出")) {
					// sb.append("退出" + hlink.getLink());
					httpClient.fetch(hlink.getLink());
					break;
				}
			}
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success";
	}
}
